﻿using ClientWebSocketDemo.WebApi.Models;
using ClientWebSocketDemo.WebApi.Services;

namespace ClientWebSocketDemo.WebApi.BackgroundServices
{
    public class RegisterHostedService : IHostedService
    {
        private HeartbeatService _heartbeatService;
        private ILoggerFactory _loggerFactory;
        private static Guid UniqueId = Guid.NewGuid();

        public RegisterHostedService(
            ILoggerFactory loggerFactory,
            IConfigClient configClient)
        {
            _loggerFactory = loggerFactory;
            _heartbeatService = new HeartbeatService(configClient);
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var logger = _loggerFactory.CreateLogger<RegisterHostedService>();

            logger.LogInformation("RegiserHostedService starting ...");
            logger.LogInformation("try to register serviceinfo to server .");

            _heartbeatService.Start(
                () =>
                {
                    return UniqueId.ToString();
                }
            );
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            var logger = _loggerFactory.CreateLogger<RegisterHostedService>();

            logger.LogInformation("RegiserHostedService stoping ...");
            logger.LogInformation("try to unregister serviceinfo from server .");
        }

        class HeartbeatResult
        {
            public bool Success { get; set; }

            public string DataVersion { get; set; }
        }
    }
}
